<template>
  <div class="main">
    <!-- 顶部工具栏 -->
    <div class="tool-bar">
      <el-form :inline="true" :model="searchInfo">
        <el-form-item label="名称" style="margin: 0">
          <el-input v-model="searchInfo.name" style="width: 140px" placeholder="名称" clearable :maxlength="64" />
        </el-form-item>
        <el-form-item label="描述" style="margin: 0 12px">
          <el-input v-model="searchInfo.desc" style="width: 140px" placeholder="描述" clearable :maxlength="64" />
        </el-form-item>
        <el-form-item label="类型" style="margin: 0 12px 0 0">
          <el-select v-model="searchInfo.operateType" placeholder="操作类型" clearable style="width: 120px">
            <el-option v-for="item in operateTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" style="margin: 0 12px 0 0">
          <el-select v-model="searchInfo.status" placeholder="操作类型" clearable style="width: 120px">
            <el-option v-for="item in taskStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <el-button @click="refreshCopyTask" type="primary">查询</el-button>
      <el-button @click="addCopyTask" type="primary">新增任务</el-button>
      <el-button type="danger" @click="warningDialogVisible = true">注意事项</el-button>
    </div>
    <!-- 表格和分页 展示任务 -->
    <div class="table-wrapper">
      <!-- 表格 -->
      <el-table class="table" :data="backupsTaskData" border show-overflow-tooltip>
        <el-table-column prop="name" label="任务名称" width="180" align="center" />
        <el-table-column prop="desc" label="描述" width="180" align="center">
          <template #default="scope">
            <span v-if="scope.row.desc">{{ scope.row.desc }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="operateType" label="操作类型" width="100" align="center">
          <template #default="scope">
            <span v-if="scope.row.operateType == 1">备份</span>
            <span v-else>还原</span>
          </template>
        </el-table-column>
        <el-table-column prop="operateTarget" label="操作对象" width="100" align="center">
          <template #default="scope">
            <span v-if="scope.row.operateTarget == 1">数据库数据</span>
            <span v-else>数据库点表</span>
          </template>
        </el-table-column>
        <el-table-column prop="filePath" label="目录" width="180" align="center" />
        <el-table-column prop="dbName" label="数据库" align="center" />
        <el-table-column prop="status" label="状态" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status == 0 ? 'info' : 'success'">
              {{ scope.row.status == 0 ? "停止" : "启动" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" align="center" />
        <el-table-column prop="tool" label="操作" fixed="right" align="center" width="300">
          <template #default="scope">
            <el-button size="small" v-if="scope.row.status == 0" @click="clickStartButton(scope.row)" type="primary"
              >启动</el-button
            >
            <el-button size="small" v-else @click="clickStopButton(scope.row)" type="danger">停止</el-button>
            <el-button size="small" @click="showTaskJob(scope.row)">运行日志</el-button>
            <el-button size="small" :disabled="scope.row.status == 1" @click="clickEditButton(scope.row)"
              >编辑</el-button
            >
            <el-button type="danger" size="small" @click="clickDeleteButton(scope.row)">删除</el-button>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty />
        </template>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        class="pagination"
        v-model:current-page="taskListPage.curPage"
        v-model:page-size="taskListPage.pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="taskListPage.total"
        @size-change="taskHandleSizeChange"
        @current-change="taskHandleCurrentChange"
      />
    </div>
    <el-dialog
      v-model="addCopyTaskDialogVisible"
      :title="editOrAddCopyTask ? '新增' : '编辑'"
      destroy-on-close
      width="550"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      @close="closeFunctionAddOrEdit"
    >
      <el-form ref="addBackupsTaskFormRef" :model="copyTaskInfo" label-width="auto" :rules="rules">
        <el-form-item label="名称" prop="name">
          <el-input v-model.trim="copyTaskInfo.name" placeholder="请输入任务名称" :maxlength="64"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input v-model.trim="copyTaskInfo.desc" placeholder="请输入描述信息" :maxlength="64"></el-input>
        </el-form-item>
        <el-form-item label="操作类型" prop="operateType">
          <el-select :disabled="!editOrAddCopyTask" v-model="copyTaskInfo.operateType" placeholder="请选择操作类型">
            <el-option v-for="item in operateTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作对象" prop="operateTarget">
          <el-select :disabled="!editOrAddCopyTask" v-model="copyTaskInfo.operateTarget" placeholder="请选择操作对象">
            <el-option
              v-for="item in taskTargetTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文件目录" prop="filePath">
          <el-input v-model.trim="copyTaskInfo.filePath" placeholder="请输入备份/恢复目录"></el-input>
        </el-form-item>
        <el-form-item label="数据库" prop="dbName">
          <el-select v-model="copyTaskInfo.dbName" placeholder="请选择数据库">
            <el-option v-for="item in dbsInfo" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="copyTaskInfo.operateType == 1 && copyTaskInfo.operateTarget == 1"
          label="时间范围"
          prop="dataTimeRange"
        >
          <el-date-picker
            v-model="copyTaskInfo.dataTimeRange"
            type="datetimerange"
            :shortcuts="shortcuts"
            start-placeholder="开始时间"
            end-placeholder="截至时间"
            format="YYYY-MM-DD HH:mm:ss"
            date-format="YYYY-MM-DD"
            time-format="HH:mm:ss"
          />
        </el-form-item>
        <el-form-item v-if="!(copyTaskInfo.operateTarget == 2)" label="线程数" prop="threadNum">
          <el-input-number style="width: 100%" v-model="copyTaskInfo.threadNum" :min="1" :max="128" :precision="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div>
          <el-button @click="addCopyTaskDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addBackupsTask"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>

    <el-drawer
      v-model="taskLogVisiable"
      title="任务日志"
      size="1200"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <el-table :data="taskLogs" border style="width: 100%; height: calc(100% - 40px)">
        <el-table-column prop="startTime" label="任务开始时间" width="180" align="center"> </el-table-column>
        <el-table-column prop="endTime" label="任务结束时间" width="180" align="center">
          <template #default="scope">
            <span v-if="scope.row.endTime">{{ scope.row.endTime }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="运行结果" width="110" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.status == '1'" type="primary">成功</el-tag>
            <el-tag v-else-if="scope.row.status == '0'" type="danger">失败</el-tag>
            <el-tag v-else type="danger">正在运行</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="filePath" label="数据目录" align="center" width="180" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="progress" label="进度" align="center">
          <template #default="scope">
            <span v-if="scope.row.status == 2">
              <el-progress :percentage="scope.row.progress" />
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          :width="currentTaskInfo.operateType == 1 && currentTaskInfo.operateTarget == 2 ? '250' : '140'"
        >
          <template #default="scope">
            <el-button
              v-if="scope.row.status == '1' && scope.row.operateType == '1' && scope.row.operateTarget == '2'"
              size="small"
              type="primary"
              @click="clickDownLoadButton(scope.row.id)"
              >下载数据库点表</el-button
            >
            <el-button @click="viewTaskMessage(scope.row.message)" size="small" type="primary">查看日志</el-button>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty />
        </template>
      </el-table>
      <el-pagination
        style="margin-top: 8px; float: right"
        v-model:current-page="logListPage.curPage"
        v-model:page-size="logListPage.pageSize"
        :page-sizes="[15, 30, 45, 60]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="logListPage.total"
        @size-change="logHandleSizeChange"
        @current-change="logHandleCurrentChange"
      />
    </el-drawer>

    <el-dialog v-model="warningDialogVisible" title="注意事项" width="600">
      <el-alert
        style="margin-bottom: 8px"
        title="设置线程数不宜多大，否则会消耗过多系统资源，建议线程数8-16"
        type="warning"
        :closable="false"
        show-icon
      />
      <el-alert
        style="margin-bottom: 8px"
        title="备份表格结构相关任务由系统默认线程数"
        type="warning"
        :closable="false"
        show-icon
      />
      <el-alert
        style="margin-bottom: 8px"
        title="文件目录表示备份数据存储的文件地址"
        type="warning"
        :closable="false"
        show-icon
      />
      <el-alert
        style="margin-bottom: 8px"
        title="执行备份任务时，时间区间不宜过长，一星期至一个月左右比较合适"
        type="warning"
        :closable="false"
        show-icon
      />
      <el-alert
        title="执行备份任务尽量选择系统空闲时间，否则可能会出现资源抢占"
        type="warning"
        :closable="false"
        show-icon
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="warningDialogVisible = false"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, reactive, defineProps, computed } from "vue";
import { showDatabases } from "@/api/index";
import {
  saveOrUpdateBackupTask,
  getBackupAndRecoverTask,
  startTask,
  stopTask,
  deleteTask,
  getTaskLog,
  downloadTagInfo,
  getRunningTaskLog,
  getRunningTask,
} from "@/api/backups";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";

import dayjs from "dayjs";
//属性值
const props = defineProps({
	dbInfo:{
		type:Object,
		default:{},
	},
	databaseInfo:{
		type:Array,
		default:[]
	}
})
//注意事项弹窗
const warningDialogVisible = ref(false);

const clickDownLoadButton = (id) => {
  let data = { id: id };
  downloadTagInfo(data)
    .then(function (response) {
      const link = document.createElement("a");
      link.href = URL.createObjectURL(response);
      link.setAttribute("download", "data.zip"); // 设置下载的文件名
      document.body.appendChild(link);
      link.click();
      link.remove();
    })
    .catch((error) => {
      console.error(error);
    });
};

//正在运行的日志定时刷新id
const taskLogIntervalId = ref(null);
const startTaskLogIntervalRefresh = () => {
  if (taskLogIntervalId.value != null) {
    clearInterval(taskLogIntervalId.value);
  }
  if (!taskLogs.value || taskLogs.value.length == 0) {
    return;
  }
  let log = taskLogs.value[0];
  let params = {
    id: log.id,
  };
  if (log.status == 2) {
    taskLogIntervalId.value = setInterval(() => {
      getRunningTaskLog(params)
        .then((res) => {
          if (res.code == 200 && res.data) {
            log.status = res.data.status;
            log.progress = res.data.progress;
            log.message = res.data.message;
            log.endTime = res.data.endTime;
            log.filePath = res.data.filePath;
            if (res.data.status != 2) {
              if (taskLogIntervalId.value != null) {
                clearInterval(taskLogIntervalId.value);
              }
            }
          } else {
            console.log("定时获取任务日志失败");
            if (taskLogIntervalId.value != null) {
              clearInterval(taskLogIntervalId.value);
            }
          }
        })
        .catch((error) => {
          console.log("定时获取任务日志失败");
          if (taskLogIntervalId.value != null) {
            clearInterval(taskLogIntervalId.value);
          }
        });
    }, 3000);
  }
};
//分页查询任务日志
const logListPage = ref({
  curPage: 1,
  pageSize: 15,
  total: 0,
});
const logHandleCurrentChange = (curPage) => {
  logListPage.value.curPage = curPage;
	getTaskLogList();
};
const logHandleSizeChange = (pageSize) => {
  logListPage.value.pageSize = pageSize;
	getTaskLogList();
};
//任务日志相关内容
const taskLogVisiable = ref(false);
const taskLogs = ref([]);
const currentTaskInfo = ref(null);
const showTaskJob = (taskInfo) => {
  taskLogVisiable.value = true;
  currentTaskInfo.value = taskInfo;
  getTaskLogList();
};
const getTaskLogList = () => {
  let data = {
    taskId: currentTaskInfo.value.id,
    current: logListPage.value.curPage,
    size: logListPage.value.pageSize,
  };
  getTaskLog(data)
    .then((res) => {
      if (res.code == 200 && res.data) {
        taskLogs.value = res.data.records;
        logListPage.value.total = res.data.total;
        logListPage.value.curPage = res.data.current;
        //检查是否开启定时刷新
        startTaskLogIntervalRefresh();
      } else {
        ElMessage.error("获取任务日志失败");
      }
    })
    .catch((e) => {
      console.log(e);
      ElMessage.error("获取任务日志失败");
    });
};

watch(taskLogVisiable, (newval) => {
  if (!newval) {
    if (taskLogIntervalId.value != null) {
      clearInterval(taskLogIntervalId.value);
      taskLogIntervalId.value = null;
    }
		getBackupsTaskByDbInfo();
  }else{
		//停止任务列表的定时刷新
		stopIntervalRefreshInfo();
	}
});

/**
 * 变量初始化
 */
//数据库信息
const store = {
	info:props.dbInfo,
	databaseInfo: props.databaseInfo
};
//备份任务相关内容
const backupsTaskData = ref([]);
const addCopyTaskDialogVisible = ref(false);
//true 新增 false 查看
const editOrAddCopyTask = ref(true);
const copyTaskInfo = ref({
  //任务名称
  name: "",
  //目录
  filePath: "",
  //数据库
  dbName: "",
  //描述信息
  desc: "",
  //任务状态
  status: 0,
  //操作类型 1 备份 2 恢复
  operateType: "1",
  //对象类型 1 备份数据库数据 2 备份数据库测点
  operateTarget: "1",
  //数据起始时间
  dataStartTime: null,
  //数据截至时间
  dataEndTime: null,
  //数据时间范围
  dataTimeRange: null,
  //线程数
  threadNum: 8,
});
const taskTargetTypeOptions = [
  {
    value: "1",
    label: "数据库数据",
  },
  {
    value: "2",
    label: "数据库点表",
  },
];
const operateTypeOptions = [
  {
    value: "1",
    label: "备份",
  },
  {
    value: "2",
    label: "还原",
  },
];
const taskStatusOptions = [
  {
    value: "1",
    label: "启动",
  },
  {
    value: "0",
    label: "停止",
  },
];
//当前连接所有的数据库信息
const dbsInfo = computed(()=>{
	let arr = [];
	store.databaseInfo.forEach(item=>{
		arr.push(item)
	})
	return arr;
})
//表单对象
const addBackupsTaskFormRef = ref(null);
//时间区间
const shortcuts = [
  {
    text: "前一周",
    value: () => {
      const end = dayjs().startOf("day").toDate();
      const start = dayjs().startOf("day").subtract(7, "day").toDate();
      return [start, end];
    },
  },
  {
    text: "前半个月",
    value: () => {
      const end = dayjs().startOf("day").toDate();
      const start = dayjs().startOf("day").subtract(15, "day").toDate();
      return [start, end];
    },
  },
  {
    text: "前一个月",
    value: () => {
      const end = dayjs().startOf("day").toDate();
      const start = dayjs().startOf("day").subtract(1, "month").toDate();
      return [start, end];
    },
  },
  {
    text: "前三个月",
    value: () => {
      const end = dayjs().startOf("day").toDate();
      const start = dayjs().startOf("day").subtract(3, "month").toDate();
      return [start, end];
    },
  },
  {
    text: "前半年",
    value: () => {
      const end = dayjs().startOf("day").toDate();
      const start = dayjs().startOf("day").subtract(6, "month").toDate();
      return [start, end];
    },
  },
];
//表单验证
const rules = {
  name: [{ required: true, message: "请输入任务名称", trigger: "blur" }],
  filePath: [{ required: true, message: "请输入备份目录", trigger: "blur" }],
  // desc: [{ required: true, message: "请输入描述", trigger: "blur" }],
  operateType: [{ required: true, message: "请选择操作类型", trigger: ["blur", "change"] }],
  operateTarget: [{ required: true, message: "请选择操作对象", trigger: ["blur", "change"] }],
  dbName: [{ required: true, message: "请选择数据库", trigger: ["blur", "change"] }],
  dataTimeRange: [{ required: true, message: "请选择数据时间范围", trigger: "change" }],
  // dataEndTime: [{ required: true, message: "请选择数据截至时间", trigger: "change" }],
  threadNum: [{ required: true, message: "请输入执行线程数", trigger: ["blur", "change"] }],
};
/**
 * 方法
 */
const taskInfoTemplate = {
  //任务名称
  name: "",
  //目录
  filePath: "",
  //数据库
  dbName: "",
  //描述信息
  desc: "",
  //任务状态
  status: 0,
  //操作类型 1 备份 2 恢复
  operateType: "1",
  //对象类型 1 备份数据库数据 2 备份数据库测点
  operateTarget: "1",
  //数据起始时间
  dataStartTime: null,
  //数据截至时间
  dataEndTime: null,
  //线程数
  threadNum: 8,
};
//新增备份任务
const addCopyTask = () => {
  copyTaskInfo.value = JSON.parse(JSON.stringify(taskInfoTemplate));
  copyTaskInfo.value.id = "";
  editOrAddCopyTask.value = true;
  addCopyTaskDialogVisible.value = true;
};

const closeFunctionAddOrEdit = () => {
  if (addBackupsTaskFormRef.value) {
    addBackupsTaskFormRef.value.clearValidate();
  }
};

//刷新备份任务数据
const refreshCopyTask = () => {
  getBackupsTaskByDbInfo();
};

/**
 * 查询过滤条件
 */
const searchInfo = reactive({
  name: "",
  desc: "",
  operateType: "",
  status: "",
});

//获取任务信息分页配置
const taskListPage = ref({
  curPage: 1,
  pageSize: 10,
  total: 0,
});
//当前页改变
const taskHandleCurrentChange = (curPage) => {
  taskListPage.value.curPage = curPage;
  getBackupsTaskByDbInfo();
};
//每页数量该表
const taskHandleSizeChange = (pageSize) => {
  taskListPage.value.pageSize = pageSize;
  getBackupsTaskByDbInfo();
};

//获取相关的任务信息
const getBackupsTaskByDbInfo = () => {
  let data = {
    hostAndPort: store.info.host + ":" + store.info.port,
    current: taskListPage.value.curPage,
    size: taskListPage.value.pageSize,
    name: searchInfo.name,
    desc: searchInfo.desc,
    operateType: searchInfo.operateType ? Number(searchInfo.operateType) : -1,
    status: searchInfo.status ? Number(searchInfo.status) : -1,
  };
  getBackupAndRecoverTask(data)
    .then((res) => {
      if (res.code == 200 && res.data) {
        backupsTaskData.value = res.data.records;
        let flag = false;
        backupsTaskData.value.forEach((item) => {
          item.operateTarget += "";
          item.operateType += "";
          if (item.status == 1) {
            currentRunningTaskId.value = item.id;
            startIntervalRefreshInfo();
            flag = true;
          }
        });
        if (!flag) {
          stopIntervalRefreshInfo();
        }
        taskListPage.value.total = res.data.total;
        taskListPage.value.curPage = res.data.current;
      }
    })
    .catch((error) => {
      console.log(error);
    });
};

/**
 * 编辑任务
 */
const clickEditButton = (data) => {
  if (data.status == 1) {
    ElMessage.error("任务已启动，请先停止任务！");
    return;
  }
  copyTaskInfo.value = JSON.parse(JSON.stringify(data));
  copyTaskInfo.value.dataTimeRange = [copyTaskInfo.value.dataStartTime, copyTaskInfo.value.dataEndTime];
  editOrAddCopyTask.value = false;
  addCopyTaskDialogVisible.value = true;
};

/**
 * 删除备份任务
 */
const clickDeleteButton = (data) => {
  if (data.status == 1) {
    ElMessage.error("任务已启动，请先停止任务！");
    return;
  }
  ElMessageBox.confirm("删除任务，任务运行日志自动删除，确认要删除?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    let params = {
      id: data.id,
    };
    deleteTask(params)
      .then((res) => {
        if (res.code == 200 && res.data) {
          ElMessage.success("删除成功");
        } else {
          ElMessage.error("删除失败：" + res.msg);
        }
        getBackupsTaskByDbInfo();
      })
      .catch((error) => {
        ElMessage.error("删除失败");
        console.log(error);
      });
  });
};

const clickStopButton = (data) => {
  ElMessageBox.confirm("任务正在运行，确认终止任务？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    let params = {
      id: data.id,
    };
    stopTask(params)
      .then((res) => {
        if (res.code == 200 && res.data) {
          ElMessage.success("任务停止成功");
          data.status = 0;
        } else {
          ElMessage.error("任务停止失败:" + res.msg);
        }
      })
      .catch((error) => {
        ElMessage.error("任务停止失败！");
        console.log(error);
      });
  });
};
//定时获取正在运行的任务的信息
const currentRunningTaskId = ref(null);
const intervalId = ref(null);
const startIntervalRefreshInfo = () => {
  if (intervalId.value != null) {
    clearInterval(intervalId.value);
  }
	if (!currentRunningTaskId.value) {
    return;
  }
  intervalId.value = setInterval(() => {
    getRunningTaskInfo();
  }, 3000);
};

const stopIntervalRefreshInfo = () => {
  if (intervalId.value != null) {
    clearInterval(intervalId.value);
  }
};

const getRunningTaskInfo = () => {
  let data = {
    id: currentRunningTaskId.value,
  };
  getRunningTask(data)
    .then((res) => {
      if (res.code == 200 && res.data) {
        let tableData = backupsTaskData.value;
        for (let i = 0; i < tableData.length; i++) {
          if (tableData[i].id == data.id) {
            tableData[i].status = res.data.status;
            break;
          }
        }
        if (res.data.status != 1) {
          stopIntervalRefreshInfo();
        }
      } else {
        ElMessage.error("获取任务信息失败:" + res.msg);
        stopIntervalRefreshInfo();
      }
    })
    .catch((error) => {
      ElMessage.error("获取任务信息失败");
      console.log(error);
      stopIntervalRefreshInfo();
    });
};

/**
 * 启动任务
 * @param data 任务信息
 */
const clickStartButton = (data) => {
  let message = "";
  if (data.operateType == 1 && data.operateTarget == 1) {
    message = "备份数据任务会消耗较多资源，请确认是否继续？";
  } else if (data.operateType == 2 && data.operateTarget == 1) {
    message = "恢复数据任务会消耗较多资源并会覆盖同时刻数据，请确认是否继续？";
  } else if (data.operateType == 1 && data.operateTarget == 2) {
    message = "备份表格任务会消耗较多资源，请确认是否继续？";
  } else {
    message = "恢复表格不会覆盖原有表格，请确认是否继续？";
  }
  ElMessageBox.confirm(message, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    let postData = { ...data };
    postData.dbConfig = {
      host: store.info.host,
      port: store.info.port,
      username: store.info.username,
      password: store.info.password,
    };
    startTask(postData)
      .then((res) => {
        if (res.code == 200 && res.data) {
          ElMessage.success("任务启动成功");
          data.status = 1;
          currentRunningTaskId.value = data.id;
          //开始定时刷新任务,定时刷新这个启动的任务的任务状态
          startIntervalRefreshInfo();
        } else {
          ElMessage.error("任务启动失败:" + res.msg);
        }
      })
      .catch((error) => {
        ElMessage.error("任务启动失败！");
        console.log(error);
      });
  });
};

const addBackupsTask = () => {
  if (!addBackupsTaskFormRef.value) {
    return;
  }
  addBackupsTaskFormRef.value.validate((valid) => {
    if (valid) {
      let data = copyTaskInfo.value;
      if (data.operateTarget == "1" && data.operateType == "1") {
        data.dataStartTime = dayjs(data.dataTimeRange[0]).format("YYYY-MM-DD HH:mm:ss.SSS");
        data.dataEndTime = dayjs(data.dataTimeRange[1]).format("YYYY-MM-DD HH:mm:ss.SSS");
      }
      data.hostAndPort = store.info.host + ":" + store.info.port;
      saveOrUpdateBackupTask(data)
        .then((res) => {
          if (res.code == 200 && res.data) {
            ElMessage.success("保存成功");
            getBackupsTaskByDbInfo();
            addCopyTaskDialogVisible.value = false;
          } else {
            ElMessage.error("保存失败：" + res.msg);
          }
        })
        .catch((error) => {
          ElMessage.error("保存失败：" + error);
          addCopyTaskDialogVisible.value = false;
        });
    }
  });
};

const viewTaskMessage = (message) => {
  let messageCopy = '<pre style="width: 520px;overflow:auto;">' + message + "</pre>";
  ElNotification({
    title: "日志详情",
    dangerouslyUseHTMLString: true,
    message: messageCopy,
    customClass: "elnotification-custom",
  });
};

/**
 * 生命周期
 */
//初始化
onMounted(() => {
  getBackupsTaskByDbInfo();
});
</script>
<style>
.elnotification-custom {
  width: 600px;
  overflow: auto;
}
</style>
<style lang="less" scoped>
.main {
  width: 100%;
  height: 100%;

  .tool-bar {
    padding: 2px;
    margin-bottom: 12px;
    display: flex;
  }

  .table-wrapper {
    height: calc(100% - 64px);
    position: relative;
    .table {
      width: calc(100% - 4px);
      height: calc(100% - 23px);
    }
    .pagination {
      margin-top: 6px;
      position: absolute;
      right: 6px;
    }
  }

  :deep(.el-drawer__header) {
    margin-bottom: 0;
  }
}
</style>
